import React from 'react'
import { Tree, Button, message, Breadcrumb, Modal } from 'antd'
import $ from 'jquery'
import moment from 'moment'
import Config from '../../common/config'
import server from '../server'

const TreeNode = Tree.TreeNode
const config = new Config()
const token = sessionStorage.getItem('token')
let UserInfo = sessionStorage.getItem('UserInfo')
UserInfo = UserInfo ? JSON.parse(UserInfo) : {}
const root = UserInfo.root
const auth = root ? {} : (UserInfo.auth ? (UserInfo.auth[server.serverName] || {}) : {})

class DepartmentAuth extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      record: this.props.location.state,
      authTree: [],//权限树
      selected: [],//选择的权限
      deepName: '',//位置
      authNumber: []//拥有权限的权限编号
    };
  }
  componentWillMount() {
    // console.log(this.state.record)
    return Promise.all([
      Promise.resolve($.ajax({
        url: `${config.Priviliege}/authority/tree`,
        type: "get",
        headers: { Authorization: 'Bearer ' + token },
      })),
      Promise.resolve($.ajax({
        url: `${config.Priviliege}/authority/getDpAuth`,
        type: "get",
        headers: { Authorization: 'Bearer ' + token },
        data: {
          number: this.state.record.number,
        }
      })),
    ]).then(data => {
      // console.log(data)
      if (data[0].code == 200 && data[1].code == 200) {
        if (data[1].deepName) {
          const deepName = data[1].deepName.map(value => {
            return value.name
          }).join(' > ')
          this.state.deepName = deepName
        }
        if (data[1].auth) {
          const selected = data[1].auth.map(value => {
            return value.number
          })
          this.state.selected = selected
        }
        this.setState({
          authNumber: data[0].authNumber,
          authTree: data[0].authority,
        })
      } else {
        message.error('服务器繁忙')
      }
    }).catch(err => {
      console.log(err)
      message.error('发生错误')
    })
  }

  //生成树选择组件
  nodeTree(arr) {
    return arr.map(value => {
      return <TreeNode
        key={value.number}
        title={value.name}
      >
        {
          value.children ? this.nodeTree(value.children) : ''
        }
      </TreeNode>
    })
  }

  saveData() {
    const { selected: newAuth, record } = this.state
    if (root || auth['/authority/department']) {
      Modal.confirm({
        title: '确认保存',
        content: '确认保存并返回部门管理页面吗？',
        onCancel: () => {
          console.log('取消');
        },
        onOk: () => {
          return Promise.resolve($.ajax({
            url: `${config.Priviliege}/authority/department`,
            type: 'post',
            headers: { Authorization: 'Bearer ' + token },
            data: {
              number: record.number,
              newAuth: JSON.stringify(newAuth)
            }
          })).then(res => {
            if (res.code == 200) {
              message.info('设置成功')
              window.location.hash = '/department';
            } else if (res.code == 201) {
              message.info(res.msg)
            } else {
              message.info('服务器繁忙')
            }
          }).catch(err => {
            message.info('发生错误')
          })
        }
      });
    } else {
      message.info('无权限')
      window.location.hash = '/department'
    }
  }
  cancelSave() {
    window.location.hash = '/department';
  }
  onCheck(key, e) {
    const { selected, authNumber } = this.state
    let newSelected
    const preKey = e.node.props.eventKey
    const deepKey = preKey.split('-').map((value, index, arr) => arr.slice(0, index + 1).join('-')).slice(1)
    console.log(deepKey)
    if (e.checked) {
      console.log(selected)
      selected.push(...deepKey)
      authNumber.forEach(element => {
        let regexp = new RegExp(`^${preKey}-`)
        if (regexp.test(element)) {
          selected.push(element)
        }
      })
      newSelected = [...new Set(selected)]
    } else {
      newSelected = selected.filter(value => !(value.includes(preKey + '-') || value == preKey))
    }
    this.setState({
      selected: newSelected
    })
  }
  render() {
    const { authTree, deepName, selected } = this.state
    console.log(selected)
    return (
      <div className="container">
        <div className="box" style={{ maxWidth: 1000 }}>
          <div className="goods-label-cont-nav clearfix" style={{ position: 'relative' }}>
            <Breadcrumb separator=">">
              <Breadcrumb.Item>权限管理</Breadcrumb.Item>
              <Breadcrumb.Item><span className='separator-a'>部门管理</span></Breadcrumb.Item>
              <Breadcrumb.Item><span className='separator-a'>部门权限</span></Breadcrumb.Item>
            </Breadcrumb>
          </div>
          <h3>位置: {deepName}</h3>
          <div className="employeeRow">
            {(authTree && authTree.length) ? <Tree
              checkable
              // defaultExpandedKeys={selected}
              defaultExpandAll={true}
              checkStrictly
              checkedKeys={selected}
              onCheck={this.onCheck.bind(this)}
            >
              {
                this.nodeTree(authTree)
              }
            </Tree> : ''
            }
          </div>
          <div style={{ textAlign: 'right', marginTop: 10 }}>
            <Button type="primary" style={{ marginRight: 15 }} onClick={this.saveData.bind(this)} >保存</Button>
            <Button onClick={this.cancelSave.bind(this)}>取消</Button>
          </div>
        </div>
      </div>
    );
  }
}
export default DepartmentAuth;